package view;


import controller.UserController;
import model.User;
import model.common.Entity;
import model.common.Msg;
import redis.clients.jedis.Jedis;
import service.UserService;
import service.impl.UserServiceImpl;
import utils.JSONUtil;
import utils.RedisUtils;
import utils.SendEmailUtils;

import javax.mail.MessagingException;
import java.security.GeneralSecurityException;
import java.util.*;

/**
 * 用户操作界面
 * 所有和用户操作相关的内容，都放到这个类里
 */
public class UserClient extends Client {

    /**
     * 用户控制器类
     */
    private static final UserController userController = new UserController();

    private static final UserService userService = new UserServiceImpl();

    /**
     * 商品用户列表
     */
    Map<String, User> userMap = new HashMap<>();


    public UserClient() {
        /**
         * 用户实体对象
         */
        User user = new User();
    }

    /**
     * 用户登录操作页面
     * 1.使用控制台提示用户输入用户名、密码
     * 2.向服务器发送请求，并接收返回消息字符串
     * 使用setter方法把数据传递给Action
     * 调用Action的登录功能
     * 3.解析消息字符串，提示用户信息
     * 4.页面跳转：使用字符串常量作为跳转标记
     * 成功：返回上一次操作的页面
     * 失败：返回登录页面
     *
     * @return
     */
    public String showLogin() {

        System.out.println("=============欢迎登录==============");
        // 1.使用控制台提示用户输入用户名、密码
        System.out.println("请输入用户名：");
        String username = sc.nextLine();
        System.out.println("请输入密码：");
        String password = sc.nextLine();


        String result = userController.login(username, password);

        Msg msg = JSONUtil.JSON2Entity(result, Msg.class);

        if (Msg.SUCCESS.equals(msg.getType())) {//登录成功
            System.out.println(msg.getMsg());

            //new Thread("loginAudio"){
            //    public void run(){
            //        String path = Objects.requireNonNull(UserClient.class.getResource("/mp3/bgm.mp3")).getPath();
            //        try {
            //            FileInputStream stream = new FileInputStream(path);
            //            Player player = new Player(stream);
            //            player.play();
            //        } catch (FileNotFoundException | JavaLayerException e ) {
            //            throw new RuntimeException(e);
            //        }
            //
            //    }
            //}.start();


            //4.页面跳转:成功:返回上一次操作的页面
            return INDEX;
        } else {
            System.out.println(msg.getMsg());//4.页面跳转:失败:返回登录页面
            return LOGIN;
        }
    }

    public String index() {
        System.out.println("=====================用户模块======================");
        String result = userOperate("请输入操作", "1:创建用户", "2:删除用户", "3:修改用户", "4:查看用户列表", "5:查看用户详情", "I:首页");
        while (true) {
            if (result.equals("1")) {
                createUser();
                return USER;
            } else if (result.equals("2")) {
                deleteUser();
                return USER;
            } else if (result.equals("3")) {
                updateUser();
                return USER;
            } else if (result.equals("4")) {
                getUserList();
                return USER;
            } else if (result.equals("5")) {
                getUserList();
                String r = userOperate("请输入要查看的用户编号");
                User user = userMap.get(r);
                if (user != null) {
                    currentUser = user;
                }
                readUser();
                return USER;
            } else if (result.equals(EXIT))
                return EXIT;
            else if (result.equals(INDEX))
                return INDEX;
        }
    }

    public void getUserList() {
        String msg = userController.getUserList();
        Msg msgObj = JSONUtil.JSON2Entity(msg, Msg.class);
        Object obj = msgObj.getObj();   // [{}，{}]
        List<?> userList = (List<?>) obj;
        System.out.println("【用户列表】");
        System.out.println("index\t\t\t\tid\t\t\t\t\t\t\t\t\t\t\t用户名\t\t\t\t\t\t角色\t\t\t\t\t创建时间\t\t\t\t\t\t\t\t\t\t\t电话号码\t\t\t\t余额");
        System.out.println("---------------------------");
        int index = 1; //编号
        for (Object o : userList) {
            String userJson = o.toString();
            User user = JSONUtil.JSON2Entity(userJson, User.class);
            String id = user.getId();
            String username = user.getUsername();
            String role = user.getRole();
            Date create_time = user.getCreateTime();
            String phone = user.getPhone();
            Double balance = user.getBalance();
            System.out.println(index + "\t\t\t\t" + id + "\t\t\t" + username + "\t\t\t\t\t\t" + role + "\t\t\t\t\t" + sdf.format(create_time) + "\t\t\t\t\t" + phone + "\t\t\t\t\t" + balance);
            userMap.put(index + "", user);
            index++;
        }
    }

    public void createUser() {
        User user = createUserInput();
        user.setId(Entity.getUUID());
        user.setCreateTime(new Date());
        user.setDeleteTime(null);
        String create = userController.createUser(user);
        System.out.println(JSONUtil.JSON2Entity(create, Msg.class).getMsg());
    }

    public void updateUser() {
        getUserList();
        String result = userOperate("请输入要更新的用户id");
        User user = userMap.get(result);
        System.out.println("请输入要更新的字段值，无需更新的字段输入n");
        user = updateUserInput(user);
        String update = userController.updateUser(user);
        System.out.println(JSONUtil.JSON2Entity(update, Msg.class).getMsg());
    }

    public void readUser() {
        System.out.println("用户id\t\t\t\t\t\t\t\t\t\t\t\t用户名\t\t\t\t角色\t\t\t创建时间\t\t\t\t\t\t\t电话号码\t\t\t余额\t\t\t地址");
        System.out.println(currentUser.getId() + "\t\t\t\t\t" + currentUser.getUsername() + "\t\t\t\t\t" + currentUser.getRole() + "\t\t\t" + currentUser.getCreateTime() + "\t\t\t\t\t\t\t" + currentUser.getPhone() + "\t\t\t" + currentUser.getBalance() + "\t\t\t" + currentUser.getAddressIds());
    }

    public void deleteUser() {
        getUserList();
        String result = userOperate("请输入要删除的用户编号", "1:创建用户", "2:删除用户", "3:修改用户", "4:查看用户列表", "5:查看用户详情", "I:首页");
        User user = userMap.get(result);
        if (user != null) {
            userController.deleteUser(user.getId());
            System.out.println("删除用户成功");
        }
    }


    public User createUserInput() {
        User user = new User();
        System.out.println("请入用户名");
        user.setUsername(sc.next());
        System.out.println("请输入密码");
        user.setPassword(sc.next());
        System.out.println("请输入用户角色 NORMAL 普通用户 ADMIN 管理员");
        user.setRole(sc.next());
        System.out.println("请输入用户电话号码");
        user.setPhone(sc.next());
        return user;
    }


    public User updateUserInput(User user) {

        System.out.println("请输入密码");
        String password = sc.next();
        if (!"n".equals(password)) user.setPassword(password);

        System.out.println("请输入用户角色 NORMAL 普通用户 ADMIN 管理员");
        String role = sc.next();
        if (!"n".equals(role)) user.setUsername(role);


        System.out.println("请输入用户余额");
        String balance = sc.next();
        if (!"n".equals(balance)) user.setBalance(new Double(balance));

        return user;
    }

    public String showReturn() {
        System.out.println("---------------------密码找回（要求账户已绑定邮箱）----------------------");
        System.out.println("请输入你的邮箱：");
        String email = sc.next();
        // 通过邮箱查找用户是否存在
        User user = userService.getUserByEmail(email);
        if (Objects.isNull(user)) {
            System.out.println("当前用户不存在");
            return INDEX;
        }


        Jedis redisConnection = RedisUtils.getRedisConnection();
        // 检查是否已经发送验证
        if (Objects.nonNull(redisConnection.get("code-" + email))) {
            System.out.println("----------------不要频繁发送验证码------------------------------------");
            return INDEX;
        }

        String code = SendEmailUtils.authCode();
        try {
            SendEmailUtils.sendEmail(email, code);
        } catch (MessagingException | GeneralSecurityException e) {
            throw new RuntimeException(e);
        }
        // redis  缓存code
        redisConnection.set("code-" + email, code);
        redisConnection.expire("code-" + email, 60);

        System.out.println("----------------------验证码发送成功(有效期60秒)-------------------------------------");

        while (true) {
            System.out.println("请输入验证码：");
            String inputCode = sc.next();
            String redisCode = redisConnection.get("code-" + email);
            if (Objects.isNull(redisCode)) {
                System.out.println("---------------------验证码已过期--------------------------------");
                return INDEX;
            }else if (!inputCode.equals(redisCode)){
                System.out.println("--------------------验证码错误，请重试--------------------------");
                continue;
            }

            System.out.println("--------------------------验证成功------------------------------------------");
            System.out.println("--------------------------请输入你的新密码：-----------------------------");
            String newPass = sc.next();
            user.setPassword(newPass);
            userController.updateUser(user);
            System.out.println("-------------------------修改成功--------------------------------------");
            return INDEX;
        }
    }
}
